package com.example.chat.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.example.chat.model.ChatModel;
import com.example.chat.service.ChatService;
import com.example.common.common.config.filter.UserContext;
import com.example.common.common.enums.ChatTypeEnum;
import com.example.chat.entity.ChatMessage;
import com.example.chat.entity.ChatSession;
import lombok.RequiredArgsConstructor;
import com.example.chat.mapper.ChatMessageMapper;
import com.example.chat.mapper.ChatSessionMapper;
import com.example.chat.model.ChatHistoryVO;
import com.example.chat.model.ChatSessionMessageVO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/6/30 20:40
 **/
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {
    private final ChatSessionMapper chatSessionMapper;
    private final ChatMessageMapper chatMessageMapper;
    private final AIService aiService;

    @Override
    public String addChatRecord(ChatModel chatModel) {
        String chatId = chatModel.getChatId();
        String requestContent = chatModel.getContent();

        // 查询会话记录
        ChatSession chatSession = chatSessionMapper.getChatSessionByChatId(chatId);
        if (chatSession == null) {
            String title = aiService.process(requestContent, chatId, ChatTypeEnum.TITLE);
            saveNewChatSession(chatId, title);
        }

        // 调用大模型
        String answerContent = aiService.process(requestContent, chatId, null);

        // 保存对话消息
        saveChatMessage(requestContent, answerContent, chatId);
        return answerContent;

    }

    @Override
    public List<ChatHistoryVO> getChatHistory(String type) {
        String userId = UserContext.getCurrentUser().getUserId();
        List<ChatSession> chatSessions = chatSessionMapper.getCHatSessionsByUserId(userId, type);
        return chatSessions.stream().map(item -> BeanUtil.toBean(item, ChatHistoryVO.class)).toList();
    }

    @Override
    public ChatSessionMessageVO getChatSessionMessage(String chatId) {
        ChatSession chatSession = chatSessionMapper.getChatSessionByChatId(chatId);
        if (chatSession == null) {
            return null;
        }
//        Assert.notNull(chatSession, "对话记录为空");
        List<ChatMessage> chatMessages = chatMessageMapper.getChatMessageByChatId(chatId);
        return ChatSessionMessageVO.builder().chatId(chatId)
                .chatName(chatSession.getChatName()).messages(chatMessages).build();
    }

    private void saveChatMessage(String requestContent, String answerContent, String chatId) {
        ChatMessage userMessage = ChatMessage.builder()
                .messageId(UUID.randomUUID().toString())
                .chatId(chatId)
                .content(requestContent)
                .type("chat")
                .sender("user")
                .build();
        ChatMessage assistantMessage = ChatMessage.builder()
                .messageId(UUID.randomUUID().toString())
                .chatId(chatId)
                .content(answerContent)
                .type("chat")
                .sender("assistant")
                .build();
        chatSessionMapper.updateChatTime(chatId);
        chatMessageMapper.saveChatMessage(userMessage);
        chatMessageMapper.saveChatMessage(assistantMessage);
    }

    private void saveNewChatSession(String chatId, String title) {
        ChatSession chatSession = ChatSession.builder()
                .chatName(StrUtil.isBlank(title) ? "defaultName" : title)
                .chatId(chatId)
                .userId(UserContext.getCurrentUser().getUserId())
                .type("chat")
                .build();
        chatSessionMapper.insertChatSession(chatSession);
    }
}
